package icu.d4peng.basic.log;

import ch.qos.logback.classic.LoggerContext;
import icu.d4peng.basic.log.properties.LogStashProperties;
import net.logstash.logback.appender.LogstashTcpSocketAppender;
import net.logstash.logback.encoder.LogstashEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

/**
 * LogAutoConfiguration:自动配置
 *
 * @author d4peng <a href="d4peng@qq.com">d4peng@qq.com</a>
 * @since 2023.12.09
 */
@AutoConfiguration
@EnableConfigurationProperties(LogStashProperties.class)
public class LogAutoConfiguration {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogAutoConfiguration.class);

    public LogAutoConfiguration(LogStashProperties logStashProperties) {
        if (logStashProperties.isEnabled()) {
            LogstashTcpSocketAppender logstashTcpSocketAppender = new LogstashTcpSocketAppender();
            logstashTcpSocketAppender.setName("LOGSTASH");
            logstashTcpSocketAppender.addDestination(logStashProperties.getUrl() + ":" + logStashProperties.getPort());
            logstashTcpSocketAppender.setEncoder(new LogstashEncoder());
            logstashTcpSocketAppender.start();

            LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
            loggerContext.getLogger("ROOT").addAppender(logstashTcpSocketAppender);
        }
    }

}
